package ops.weixin.cp.api.impl;

import static ops.weixin.common.api.WxConsts.OAuth2Scope.SNSAPI_BASE;
import static ops.weixin.common.api.WxConsts.OAuth2Scope.SNSAPI_PRIVATEINFO;
import static ops.weixin.common.api.WxConsts.OAuth2Scope.SNSAPI_USERINFO;
import static ops.weixin.cp.constant.WxCpApiPathConsts.OAuth2.URL_OAUTH2_AUTHORIZE;

import ops.weixin.common.util.http.URIUtil;
import ops.weixin.cp.api.WxCpOAuth2Service;
import ops.weixin.cp.api.WxCpService;

/**
 * oauth2相关接口实现类.
 * 
 * @author SuM
 * @date: 2019年12月25日下午1:25:49
 */
public class WxCpOAuth2ServiceImpl implements WxCpOAuth2Service {
	private final WxCpService mainService;

	public WxCpOAuth2ServiceImpl(WxCpService mainService) {
		this.mainService = mainService;
	}

	@Override
	public String buildAuthorizationUrl(String state) {
		return this.buildAuthorizationUrl(this.mainService.getWxCpConfigStorage().getOauth2redirectUri(), state);
	}

	@Override
	public String buildAuthorizationUrl(String redirectUri, String state) {
		return this.buildAuthorizationUrl(redirectUri, state, SNSAPI_BASE);
	}

	@Override
	public String buildAuthorizationUrl(String redirectUri, String state, String scope) {
		StringBuilder url = new StringBuilder(URL_OAUTH2_AUTHORIZE);
		url.append("?appid=").append(this.mainService.getWxCpConfigStorage().getCorpId());
		url.append("&redirect_uri=").append(URIUtil.encodeURIComponent(redirectUri));
		url.append("&response_type=code");
		url.append("&scope=").append(scope);

		if (SNSAPI_PRIVATEINFO.equals(scope) || SNSAPI_USERINFO.equals(scope)) {
			url.append("&agentid=").append(this.mainService.getWxCpConfigStorage().getAgentId());
		}

		if (state != null) {
			url.append("&state=").append(state);
		}

		url.append("#wechat_redirect");
		return url.toString();
	}
}
